package school.controller.admin;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;
import school.domain.Shop;
import school.mapper.ShopMapper;
import school.support.BaseController;
import school.support.util.ParamUtils;
import tk.mybatis.mapper.entity.Example;

@Controller
@RequestMapping("shop")
public class ShopController extends BaseController {

    @Autowired
    private ShopMapper shopMapper;

    /**
     * 列表
     *
     * @param shop
     * @param pageNum
     * @param model
     * @return
     */
    @RequestMapping("list")
    public String list(Shop shop, @RequestParam(defaultValue = "1") Integer pageNum, Model model) {
        Example example = new Example(Shop.class);
        Example.Criteria criteria = example.createCriteria();
        if (shop.getName() != null) {
            criteria.andLike("name", "%" + shop.getName() + "%");
        }
        PageHelper.startPage(pageNum, pageSize);
        PageInfo<Shop> pageInfo = new PageInfo<>(shopMapper.selectByExample(example), 5);
        model.addAttribute(pageInfo);
        model.addAttribute("url", request.getRequestURI() + "?" + ParamUtils.params2String(request));
        return "shop/list";
    }


    /**
     * 详情
     *
     * @param id
     * @param model
     * @return
     */
    @RequestMapping("detail/{id}")
    public String detail(@PathVariable Integer id, Model model) {
        Shop shop = shopMapper.selectByPrimaryKey(id);
        model.addAttribute(shop);
        return "shop/detail";
    }

    /**
     * 修改
     *
     * @param shop
     * @return
     */
    @RequestMapping("update")
    public String update(Shop shop) {
        shopMapper.updateByPrimaryKeySelective(shop);
        return refresh();
    }

    /**
     * 删除
     *
     * @param id
     * @return
     */
    @RequestMapping("del/{id}")
    public String del(@PathVariable Integer id) {
        shopMapper.deleteByPrimaryKey(id);
        return refresh();
    }

    @GetMapping("add")
    public String add() {
        return "shop/add";
    }

    /**
     * 添加
     * @param shop
     * @return
     */
    @PostMapping("add")
    public String add(Shop shop) {
        shop.setMoney(0D);
        shopMapper.insertSelective(shop);
        return "redirect:list";
    }
}
